const app = getApp()
const workingGroupDB = wx.cloud.database().collection("workingGroup")
const {
  $Toast
} = require('../../dist/base/index');

Page({
  data: {
    userOpenId: '',
    userInfo: {},
    noLoginImage: '../../images/icon/login.png',
    hasUserInfo: false,
    group: {},
    isGroupLeader: false,
    groupName: '',
    pGroup: {},
    pGroupName: '',
    spinShow: false
  },
  onLoad: function(options) {
    //获取用户openId
    let that = this
    wx.cloud.callFunction({
      name: "getOpenid"
    }).then(res => {
      that.setData({
        userOpenId: res.result.event.userInfo.openId
      })
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          that.setData({
            spinShow: true
          })
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              that.setData({
                hasUserInfo: true,
                userInfo: res.userInfo
              })
              app.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
              //获取用户组
              that.getGroup()
            }
          })
        }
      }
    })
  },
  //获取用户信息回调
  getUserInfo(e) {
    if (e.detail.userInfo) {
      this.setData({
        userInfo: e.detail.userInfo,
        spinShow: true
      })
      app.globalData.userInfo = e.detail.userInfo
      this.flush()
      this.getGroup()
    }
  },
  //获取所在组
  getGroup() {
    let that = this
    wx.cloud.callFunction({
      name: 'getGroup'
    }).then(res => {
      if (res.result.length != 0) {
        that.setData({
          group: res.result[0].group[0],
          groupName: res.result[0].group[0].groupName
        })
        app.globalData.group = res.result[0].group[0]
        if (that.data.userOpenId == res.result[0].group[0]._openid) {
          that.setData({
            isGroupLeader: true
          })
        } else {
          that.setData({
            isGroupLeader: false
          })
        }
        if (res.result[0].group[0].pid) {
          that.getPgroup(res.result[0].group[0].pid)
        } else {
          app.globalData.pGroup = null
          that.setData({
            spinShow: false,
            hasUserInfo: true,
            pGroup: {},
            pGroupName: ''
          })
        }
      } else {
        that.setData({
          spinShow: false,
          hasUserInfo: true
        })
      }
    })
  },
  //获取上级组
  getPgroup(groupId) {
    let that = this
    wx.cloud.callFunction({
      name: 'getGroup',
      data: {
        groupId: groupId
      }
    }).then(res => {
      if (res.result._id) {
        that.setData({
          spinShow: false,
          hasUserInfo: true,
          pGroup: res.result,
          pGroupName: res.result.groupName
        })
        app.globalData.pGroup = res.result
      } else {
        that.setData({
          spinShow: false,
          hasUserInfo: true
        })
        app.globalData.pGroup = null
      }
    })
  },
  onShow: function() {
    if (app.globalData.flushGroup) {
      this.getGroup()
      app.globalData.flushGroup = false
    }
  },
  addGroup() {
    if (!this.data.hasUserInfo) {
      $Toast({
        content: '请先登录',
        image: '../../images/icon/despise.png'
      });
      return
    }
    let that = this
    let data = {
      type: '0'
    }
    if (that.data.groupName) {
      if (that.data.group._openid == that.data.userOpenId) {
        wx.showModal({
          title: '提示',
          content: '您是组长，该操作会解散组,是否继续?',
          success(res) {
            if (res.confirm) {
              data.groupId = that.data.group._id
              data.deleteAll = true
              wx.navigateTo({
                url: '/pages/group_add/group_add?data=' + JSON.stringify(data)
              })
            }
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '您已经有组，该操作将退出目前所在组,是否继续?',
          success(res) {
            if (res.confirm) {
              data.groupId = that.data.group._id
              data.deleteAll = false
              wx.navigateTo({
                url: '/pages/group_add/group_add?data=' + JSON.stringify(data)
              })
            }
          }
        })
      }
    } else {
      wx.navigateTo({
        url: '/pages/group_add/group_add?data=' + JSON.stringify(data)
      })
    }
  },
  editGroup() {
    if (this.data.groupName) {
      if (this.data.group._openid != this.data.userOpenId) {
        $Toast({
          content: '您没有权限',
          image: '../../images/icon/despise.png'
        });
      } else {
        let data = {
          type: '1',
          groupId: this.data.group._id,
          groupName: this.data.group.groupName
        }
        wx.navigateTo({
          url: '/pages/group_add/group_add?data=' + JSON.stringify(data)
        })
      }
    } else {
      this.noGroup()
    }
  },
  joinGroup() {
    if (!this.data.hasUserInfo) {
      $Toast({
        content: '请先登录',
        image: '../../images/icon/despise.png'
      });
      return
    }
    let data = {
      joinType: '0'
    }
    if (!this.data.groupName) {
      wx.navigateTo({
        url: '/pages/group_join/group_join?data=' + JSON.stringify(data)
      })
    } else if (this.data.group._openid == this.data.userOpenId) {
      $Toast({
        content: '组长无法加入',
        image: '../../images/icon/sad2.png'
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '您已经有组，确定要加入其他组?',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/group_join/group_join?data=' + JSON.stringify(data)
            })
          }
        }
      })
    }
  },
  resetLeader(groupId) {
    let that = this
    wx.cloud.callFunction({ //获取下级
      name: 'getSubGroup',
      data: {
        type: '0',
        groupId: groupId
      }
    }).then(res => {
      if (res.result.length > 0) {
        let groupIds = []
        for (let i = 0; i < res.result.length; i++) {
          groupIds.push(res.result[i]._id)
        }
        wx.cloud.callFunction({
          name: 'resetLeader',
          data: {
            groupIds: groupIds
          }
        }).then(res2 => {
          // console.log(res2)
        })
      }
    })
  },
  deleteGroup() {
    let that = this
    if (!this.data.groupName) {
      this.noGroup()
      return
    }
    if (this.data.group._openid != this.data.userOpenId) {
      $Toast({
        content: '您没有权限',
        image: '../../images/icon/despise.png'
      });
      return
    }
    wx.showModal({
      title: '提示',
      content: '确定删除?',
      success(res) {
        if (res.confirm) {
          wx.cloud.callFunction({ // 删除组员
              name: 'deleteGroupMember',
              data: {
                groupId: that.data.group._id,
                deleteAll: true
              }
            })
            .then(res2 => {
              workingGroupDB.doc(that.data.group._id).remove().then(res3 => { //删除组
                that.resetLeader(that.data.group._id)
                $Toast({
                  content: '删除成功',
                  image: '../../images/icon/happy.png'
                });
                that.setData({
                  group: {},
                  groupName: '',
                  pGroup: {},
                  pGroupName: ''
                })
                app.globalData.group = null
                app.globalData.pGroup = null
                that.flush()
              })
            })
        }
      }
    })
  },
  findPGroup() {
    if (!this.data.groupName) {
      this.noGroup()
      return
    }
    if (this.data.group._openid != this.data.userOpenId) {
      $Toast({
        content: '您没有权限',
        image: '../../images/icon/despise.png'
      });
      return
    }
    let that = this
    //先判断是否有下级
    wx.cloud.callFunction({
      name: 'getSubGroup',
      data: {
        type: '0',
        groupId: this.data.group._id
      }
    }).then(res => {
      if (res.result.length > 0) {
        $Toast({
          content: '您已经有下级',
          image: '../../images/icon/despise.png'
        });
      } else {
        let data = {
          joinType: '1',
          groupId: that.data.group._id
        }
        if (that.data.leaderId) {
          wx.showModal({
            title: '提示',
            content: '您已经有上级，确定要修改上级?',
            success(res2) {
              if (res2.confirm) {
                wx.navigateTo({
                  url: '/pages/group_join/group_join?data=' + JSON.stringify(data)
                })
              }
            }
          })
        } else {
          wx.navigateTo({
            url: '/pages/group_join/group_join?data=' + JSON.stringify(data)
          })
        }
      }
    })
  },
  createLink() {
    if (!this.data.groupName) {
      this.noGroup()
      return
    }
    let that = this
    wx.showActionSheet({
      itemList: ['复制'],
      success(res) {
        if (res.tapIndex == 0) {
          wx.cloud.callFunction({
              name: 'generateInviteCode',
              data: {
                type: 'encode',
                groupId: that.data.group._id
              }
            })
            .then(res2 => {
              wx.setClipboardData({
                data: res2.result
              })
            })
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  viewJunior() {
    if (!this.data.groupName) {
      this.noGroup()
      return
    }
    if (this.data.group._openid != this.data.userOpenId) {
      $Toast({
        content: '您没有权限',
        image: '../../images/icon/despise.png'
      });
      return
    }
    wx.navigateTo({
      url: '/pages/record_all/record_all'
    })
  },
  noGroup() {
    $Toast({
      content: '没有组',
      image: '../../images/icon/despise.png'
    });
  },
  flush() {
    app.globalData.flushView = true
    app.globalData.flushExport = true
    app.globalData.flushManage = true
    app.globalData.flushQrCode = true
  }
})